<template>
  <div class='container'>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{title}}</span>
      </div>
      <!-- 学科选项 -->
      <el-form size="small" :model="formParams" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <el-form-item label="学科：" prop="subjectID">
          <el-select v-model="formParams.subjectID" placeholder="请选择">
            <el-option :value="item.value" :label="item.label" v-for='item in testList' :key="item.value" @click.native="getDirect(item.value)"></el-option>
          </el-select>
        </el-form-item>
        <!-- 目录选项 -->
        <el-form-item label="目录：" prop="directoryName">
          <el-select v-model="formParams.directoryName" placeholder="请选择">
            <el-option v-for='item in directList' :key="item.value" :label="item.label" :value="item.value" @click.native='getcatalogid(item.value)'></el-option>
          </el-select>
        </el-form-item>
        <!-- 企业选项 -->
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select v-model="formParams.enterpriseID" placeholder="请选择">
            <el-option v-for="item in bankList" :key="item.id" :label="item.company" :value="item.id" @click.native='getBankID(item.id)'></el-option>
          </el-select>
        </el-form-item>
        <!-- 城市选项 -->
        <div class="city">
          <el-form-item label="城市：" prop="city" style="width=50px">
            <el-select v-model="formParams.province" placeholder="请选择">
              <el-option v-for="item in datas" :key="item" :value="item" @click.native="getCity(item)"></el-option>
            </el-select>
            <el-select v-model="formParams.city" placeholder="请选择">
              <el-option v-for="item in underCity" :key="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <!-- 方向选项 -->
        <el-form-item label="方向：" prop="direction">
          <el-select v-model="formParams.direction" placeholder="请选择活动区域">
            <el-option v-for="item in direction" :key='item' :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <!-- 选择题型难度 -->
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group v-model="formParams.questionType">
            <el-radio label="1">单选</el-radio>
            <el-radio label="2">多选</el-radio>
            <el-radio label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="formParams.difficulty">
            <el-radio label="1">简单</el-radio>
            <el-radio label="2">一般</el-radio>
            <el-radio label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 富文本区域 -->
        <el-form-item label="题干：" prop="question">
          <quill-editor @focus="rulesee1" @blur='rulesee1' ref='rich1' v-model='formParams.question' class='rich-text' :options="editorOption"></quill-editor>
        </el-form-item>
        <!-- 选择题开始 -->
        <div v-if="formParams.questionType==='1'">
          <el-form-item label="选项：">
            <template>
              <!-- 选项A -->
              <div class="chooseBar" v-for=" (item ,index) in formParams.options" :key="item.code">
                <span>
                  <el-radio @change=getstatus(item,index) v-model="item.isRight" :label="true">{{item.code}}：</el-radio>
                </span>
                <span>
                  <el-input v-model="formParams.options[index].title"></el-input>
                </span>
                <!-- 上传图片 -->
                <span>
                  <el-upload class="avatar-uploader" action="" :show-file-list="false">
                    <img v-if="false" :src="true" class="avatar">
                    <i v-else>上传图片</i>
                    <i class="el-icon-circle-close"></i>
                  </el-upload>
                </span>
              </div>
              <el-button type="danger" disabled>+增加选项与答案</el-button>
            </template>
          </el-form-item>
        </div>
        <!-- 选择题结束 -->
        <!-- 选择题开始 -->
        <div v-else-if="formParams.questionType==='2'">
          <el-form-item label="选项：">
            <template>
              <!-- 选项A -->
              <div class="chooseBar" v-for="(item , index) in formParams.options" :key="item.code">
                <span>
                  <el-checkbox @change=getstatus(item,index) v-model="formParams.options[index].isRight" :key='item.code' :label="item.code+'：'"></el-checkbox>
                </span>
                <span>
                  <el-input v-model="formParams.options[index].title"></el-input>
                </span>
                <!-- 上传图片 -->
                <span>
                  <el-upload class="avatar-uploader" action="" :show-file-list="false" :on-error="handleAvatarSuccess">
                    <img v-if="false" :src="true" class="avatar">
                    <i v-else>上传图片</i>
                    <i class="el-icon-circle-close"></i>
                  </el-upload>
                </span>
              </div>
              <el-button type="danger" @click.stop="getletter">+增加选项与答案</el-button>
            </template>
          </el-form-item>
        </div>
        <!-- 选择题结束 -->
        <!-- 解析视频输入框 -->
        <div class="video" v-if="id">
          <el-form-item label="解析视频：" prop="videoURL">
            <el-input v-model="formParams.videoURL" :value="formParams.videoURL"></el-input>
          </el-form-item>
        </div>
        <div class="video" v-else>
          <el-form-item label="解析视频：">
            <el-input v-model="formParams.videoURL" :value="formParams.videoURL"></el-input>
          </el-form-item>
        </div>
        <!-- 富文本区域 -->
        <el-form-item label="答案解析：" prop="answer">
          <quill-editor @focus="rulesee2" @blur='rulesee2' ref='rich2' v-model='formParams.answer' class='rich-text' :options="editorOption"></quill-editor>
        </el-form-item>
        <!-- 题目备注 -->
        <div class="note" v-if="id">
          <el-form-item label="题目备注：" prop="remarks">
            <el-input type="textarea" v-model="formParams.remarks"></el-input>
          </el-form-item>
        </div>
        <div class="note" v-else>
          <el-form-item label="题目备注：">
            <el-input type="textarea" v-model="formParams.remarks"></el-input>
          </el-form-item>
        </div>
        <!-- 试题录入标签 -->
        <div>
          <template>
            <el-form-item label="试题标签：" prop="tags">
              <!-- 错误在这里 -->
              <el-select v-model="formParams.tags" multiple filterable allow-create default-first-option placeholder="请选择试题标签">
                <el-option v-for='(item) in content' :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </div>
        <!-- 按钮 -->
        <el-form-item>
          <el-button type="primary" @click='submitForm'>确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 导入富文本编辑器
import { quillEditor } from 'vue-quill-editor'
// 题型难度 和单选多选数据
import { direction } from '@/api/hmmm/constants.js'
//  ,  questionType,difficulty,
// 导入富文本相关的样式和组件
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// 导入接口
import { add, detail, update } from '@/api/hmmm/questions.js'
import { simple } from '@/api/hmmm/subjects.js'
import { simple as simple1 } from '@/api/hmmm/directorys.js'
import { list } from '@/api/hmmm/companys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { simple as tagsList } from '@/api/hmmm/tags.js'
export default {
  name: 'question-new',
  components: {
    quillEditor
  },
  data () {
    return {
      // 动态样式
      imageUrl: '',
      // 标签中使用的数据
      content: [],
      // 提交表时需要提交的数据
      formParams: {
        // 答案解析
        answer: '',
        // 目录id 已获取
        catalogID: null,
        // 下线城市信息 已获取
        city: '',
        // 简单困难一般 已获取
        difficulty: '1',
        // 就业方向数据 已获取
        direction: '',
        // 企业id 已获取
        enterpriseID: null,
        // 选项信息
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }],
        // 城市信息 已获取
        province: '',
        // 题干信息
        question: '',
        // 单选 多选数据 已获取
        questionType: '1',
        // 题目备注信息 已获取
        remarks: null,
        // 学科名字
        subjectName: '',
        // 目录名
        directoryName: '',
        // 学科id 已获取
        subjectID: '',
        // 试题标签
        tags: [],
        // 解释视频 已经获取
        videoURL: null
      },
      id: null,
      // 外部标签状态位
      tags: [],
      letterpush: [
        { isRight: false, code: 'A', title: '', img: '' },
        { isRight: false, code: 'B ', title: '', img: '' },
        { isRight: false, code: 'C', title: '', img: '' },
        { isRight: false, code: 'D', title: '', img: '' },
        { isRight: false, code: 'E', title: '', img: '' },
        { isRight: false, code: 'F', title: '', img: '' },
        { isRight: false, code: 'G', title: '', img: '' },
        { isRight: false, code: 'H', title: '', img: '' },
        { isRight: false, code: 'I', title: '', img: '' },
        { isRight: false, code: 'J', title: '', img: '' },
        { isRight: false, code: 'K', title: '', img: '' },
        { isRight: false, code: 'L', title: '', img: '' },
        { isRight: false, code: 'M', title: '', img: '' },
        { isRight: false, code: 'N', title: '', img: '' },
        { isRight: false, code: 'O', title: '', img: '' },
        { isRight: false, code: 'P', title: '', img: '' },
        { isRight: false, code: 'Q', title: '', img: '' },
        { isRight: false, code: 'R', title: '', img: '' },
        { isRight: false, code: 'S', title: '', img: '' },
        { isRight: false, code: 'T', title: '', img: '' },
        { isRight: false, code: 'U', title: '', img: '' },
        { isRight: false, code: 'V', title: '', img: '' },
        { isRight: false, code: 'W', title: '', img: '' },
        { isRight: false, code: 'X', title: '', img: '' },
        { isRight: false, code: 'Y', title: '', img: '' },
        { isRight: false, code: 'Z', title: '', img: '' }
      ],
      // 方向列表的数据 接收
      direction: direction,
      // 所有线下城市的数据 接收
      underCity: '',
      // 所有城市数据 接收
      datas: [],
      // 银行数据 接收
      bankList: [],
      // 学科科目名称 数据 接收
      testList: [],
      // 目录数据 接收
      directList: [],
      // url 地址
      posterURL: '',
      // 表单验证规则
      rules: {
        // 非空验证
        difficulty: [
          { required: true, message: '请输入学科名称', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请输入学科名称', trigger: 'change' }
        ],
        subjectID: [
          { required: true, message: '请输入学科名称', trigger: 'change' }
        ],
        // 目录规则验证
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'change' }
        ],
        // 银行信息验证
        enterpriseID: [
          { required: true, message: '请选择企业名称', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择城市名称', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选中活动名称', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干内容', trigger: 'blur' }
        ],
        videoURL: [{
          required: true, message: '请输入视频解析地址', trigger: 'blur'
        }],
        answer: [
          {
            required: true, message: '请输入答案解析内容', trigger: 'blur'
          }
        ],
        remarks: [
          { required: true, message: '请输入题目备注内容', trigger: 'blur' }
        ],
        tags: [
          { required: true, message: '请输入标签内容', trigger: 'change' }
        ]
      },
      // 富文本配置对象
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image']
          ]
        }
      }
    }
  },
  methods: {
    rulesee2 () {
      this.$refs.ruleForm.validateField('answer')
    },
    rulesee1 () {
      this.$refs.ruleForm.validateField('question')
    },
    // 根据状态改变单选按钮的反选
    changeRadioSelect () {
      this.formParams.options.forEach((item, i) => {
        // console.log(this.formParams.options)
      })
    },
    // 根据id获取详情页
    async detail (id) {
      if (this.$route.query.id) {
        this.id = true
        try {
          const ret = await detail(id)
          // console.log(ret)
          this.formParams = ret.data
          this.formParams.tags = this.formParams.tags.split(',')
          this.tagsList()
          this.getBankList()
          this.changeRadioSelect()
          this.changeRadio()
          // 判断单选框的条件
          if (this.formParams.questionType === '2') {
            // 判断复选框的选中条件
            this.formParams.options.forEach((item, index) => {
              if (item.isRight === 1) {
                item.isRight = true
              }
            })
          } else if (this.formParams.questionType === '1') {
            // 单选框的值
            this.formParams.options.forEach((item, index) => {
              if (item.isRight === 1) {
              }
            })
          }
        } catch (e) {
          console.log(e)
          this.$message.error('获取详情页失败')
        }
      }
    },
    // 获取组组件内的数据
    async submitForm () {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          // console.log('---')
          if (this.$route.query.id) {
            // 判断没有remark 但是有videourl
            // this.formParams.remarks.length === 0 && this.formParams.videoURL.length === 0
            // if (this.formParams.remarks.length === 0 && this.formParams.videoURL.length === 0) {
            //   this.formParams.tags = this.formParams.tags.join(',')
            //   const { remarks, videoURL, ...obj1 } = this.formParams
            //   console.log(obj1)
            //   await update(obj1)
            //   this.formParams.tags = this.formParams.tags.split(',')
            //   this.$router.push('/questions/list')
            //   this.$message.success('修改成功')
            // } else if (this.formParams.remarks.length === 0) {
            //   this.formParams.tags = this.formParams.tags.join(',')
            //   const { remarks, ...obj1 } = this.formParams
            //   console.log(remarks)
            //   await update(obj1)
            //   this.formParams.tags = this.formParams.tags.split(',')
            //   this.$router.push('/questions/list')
            //   this.$message.success('修改成功')
            // } else if (this.formParams.videoURL.length === 0) {
            //   this.formParams.tags = this.formParams.tags.join(',')
            //   const { videoURL, ...obj1 } = this.formParams
            //   console.log(videoURL)
            //   await update(obj1)
            this.formParams.tags = this.formParams.tags.join(',')
            const ret = this.formParams
            await update(ret)
            this.$router.push('/questions/list')
            this.$message.success('修改成功')
            // }
            return
          }
          try {
            // 提交前更改标签样式
            this.formParams.tags = this.formParams.tags.join(',')
            await add(this.formParams)
            this.$router.push('/questions/list')
            this.$message.success('发布成功')
          } catch (e) {
            console.log(e)
            this.$message.error('添加文章失败')
          }
        } else {
          console.log('表单验证失败')
        }
      })
    },
    // 获取单选框选中的状态
    getstatus (item, index) {
      // 数据发生改变是如果是单选框把他的值都改为false 然后点击的那一个改为true
      if (this.formParams.questionType === '1') {
        this.formParams.options.forEach((items, i) => {
          items.isRight = false
        })
        item.isRight = true
      } else if (this.formParams.questionType === '2') {
        // console.log(this.formParams.options)
      }

      // 单选框状态的改变
      // if (this.formParams.questionType === '1') {
      //   if (item.code === this.formParams.options[index].code) {
      //     for (var i = 0; i < item.length; i++) {
      //       this.formParams.options[i].isRight = false
      //     }
      //     this.formParams.options[index].isRight = true
      //     console.log(this.formParams.options)
      //   }
      // } else if (this.formParams.questionType === '2') {
      //   // console.log(this.formParams.options)
      // }
    },
    // 追加选择的选项
    getletter () {
      var num = 1
      // console.log('222')
      if (num === 1) {
        if (this.formParams.options.length > 25) {
          this.formParams.options.length = 25
        }
        const ret = this.letterpush[this.formParams.options.length]
        this.formParams.options.push(ret)
        num = 0
      }
      // console.log('111')
    },
    // 获取银行的id
    getBankID (id) {
      this.formParams.enterpriseID = id
    },
    // 获取科目的id
    getcatalogid (id) {
      this.formParams.catalogID = id
    },
    // 照片成功后回调
    handleAvatarSuccess () {
      // console.log('---')
    },
    // 获取所有城市的放法
    provinces () {
      const ret = provinces()
      this.datas = ret
    },
    // 获取下线城市方法
    getCity (city) {
      // this.formListParams.underCity = null
      this.formParams.city = null
      const ret = citys(city)
      this.underCity = ret
    },
    // 获取银行数据
    async getBankList () {
      try {
        const ret = await list({
          pagesize: 10000
        })
        this.bankList = ret.data.items
        // console.log(this.bankList)
        const res = ret.data.items
        for (let i = 0; i < res.length; i++) {
          if (this.formParams.enterpriseID === res[i].id) {
            this.formParams.company = res[i].company
          }
        }
      } catch (e) {
        console.log(e)
        this.$message.error('获取银行列表失败')
      }
    },
    // 页面加载时获取学科科目列表
    async getlist () {
      try {
        const ret = await simple()
        this.testList = ret.data
        // console.log(ret)
      } catch (e) {
        console.log(e)
        this.$message.error('获取试题列表失败')
      }
    },
    //  根据学科id 获取目录数据
    async getDirect (id) {
      this.formParams.directoryName = null
      try {
        const ret = await simple1({
          subjectID: id
        })
        this.directList = ret.data
        // // 把学科的id 赋值给表单数据
        const subjectid = this.formParams.subjectID
        const res = await tagsList({ subjectID: subjectid })
        this.content = res.data
      } catch (e) {
        console.log(e)
        this.$message.error('获取目录失败')
      }
    },
    // 获取标签列表
    async tagsList () {
      try {
        const id = this.formParams.subjectID
        const ret = await tagsList({ subjectID: id })
        this.content = ret.data
      } catch (e) {
        console.log(e)
        this.$message.error('获取标签列表失败')
      }
    },
    // 遍历单选状态修改
    changeRadio () {
      this.formParams.options.forEach((item) => {
        if (!this.formParams.questionType === 1) return
        if (item.isRight === 1) {
          item.isRight = true
        } else {
          // 如果为0改为false
          item.isRight = false
        }
      })
    }
  },
  created () {
    // 获取企业列表
    if (!this.$route.query.id) {
      this.getBankList()
    }
    this.getlist()
    this.provinces()
    const id = this.$route.query.id
    this.detail({ id: id })
  },
  mounted () {
    this.$refs.rich1.quill.enable(false)
    this.$refs.rich2.quill.enable(false)
    setTimeout(() => {
      this.$refs.rich1.quill.enable(true)
      this.$refs.rich2.quill.enable(true)
      this.$refs.rich1.quill.blur()
      this.$refs.rich2.quill.blur()
    }, 500)
  },
  computed: {
    // 动态生成表单的标题
    title () {
      return this.formParams.id ? '编辑文章' : '发布文章'
    }
  },
  // 监听路径的改变 重新赋值
  watch: {
    $route (to) {
      if (!to.query.id) {
        this.$nextTick(() => {
          this.$refs.ruleForm.clearValidate()
        })
        this.id = false
        // 发布文章
        this.formParams.options = [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }]
        this.formParams.videoURL = ''
        this.formParams.city = null
        this.formParams.id = null
        this.formParams.questionType = '1'
        this.formParams.difficulty = '1'
        this.formParams.tags = ''
        this.content = ''
        this.formParams.province = ''
        this.$refs.ruleForm.resetFields()
        // 重置表单
      }
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep.container {
  padding: 20px;
  // 题目备注
  .grids {
    .el-select-dropdown__item {
      color: gray;
      text-align: center;
    }
  }
  .note {
    width: 520px;
  }
  .city {
    .el-select {
      width: 195px;
      margin-right: 10px;
    }
  }
  // 视频解析样式
  .video {
    .el-input {
      width: 400px;
    }
  }
  // 富文本编辑样式
  .rich-text {
    padding: 15px 12px 15px 0px;
    min-height: 200px;
    .ql-container {
      min-height: 200px;
    }
  }
  // 选择按钮的样式
  .chooseBar {
    position: relative;
    margin: 0px 0px 20px 0px;
    height: 60px;
    .el-checkbox {
      vertical-align: middle;
    }
    .el-input {
      width: 240px;
    }
    span {
      float: left;
      &:nth-child(1) {
        margin-top: 1px;
      }
      &:nth-child(3) {
        :hover {
          border-color: #409eff;
        }
        position: absolute;
        left: 300px;
        bottom: 10px;
        i:nth-child(1) {
          text-align: center;
          font-style: normal;
        }
        i:nth-child(2) {
          position: absolute;
          right: -5px;
          top: -5px;
        }
      }
    }
    .avatar-uploader {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      width: 100px;
      height: 60px;
      line-height: 60px;
      text-align: center;
    }
  }
}
::v-deep .el-select {
  width: 400px;
  height: 36px;
  .el-input__inner {
    height: 36px;
  }
}
</style>
